using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 项目管理对话框
    /// </summary>
    public partial class ProjectManagementDialog : Window
    {
        private readonly ILogger<ProjectManagementDialog> _logger;
        private readonly IDataStorageService _dataStorage;
        private readonly ObservableCollection<ProjectViewModel> _projects = new();
        private readonly CollectionViewSource _projectsViewSource = new();

        // 事件
        public event EventHandler<Project>? ProjectSelected;

        public ProjectManagementDialog(
            ILogger<ProjectManagementDialog> logger,
            IDataStorageService dataStorage)
        {
            InitializeComponent();
            _logger = logger;
            _dataStorage = dataStorage;
            
            InitializeUI();
            LoadProjectsAsync();
        }

        private void InitializeUI()
        {
            // 设置数据源
            _projectsViewSource.Source = _projects;
            ProjectsDataGrid.ItemsSource = _projectsViewSource.View;
            
            // 设置过滤
            _projectsViewSource.Filter += ProjectsViewSource_Filter;
            
            UpdateStatus("就绪", Brushes.Green);
            _logger.LogInformation("项目管理对话框已初始化");
        }

        private async void LoadProjectsAsync()
        {
            try
            {
                UpdateStatus("加载项目列表...", Brushes.Orange);
                
                var projects = await _dataStorage.GetProjectsAsync();
                
                _projects.Clear();
                foreach (var project in projects)
                {
                    _projects.Add(new ProjectViewModel(project));
                }
                
                ProjectCountText.Text = $"共 {_projects.Count} 个项目";
                UpdateSelectedCount();
                UpdateStatus("加载完成", Brushes.Green);
                
                _logger.LogInformation($"已加载 {_projects.Count} 个项目");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载项目列表失败");
                UpdateStatus("加载失败", Brushes.Red);
                MessageBox.Show($"加载项目列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ProjectsViewSource_Filter(object sender, FilterEventArgs e)
        {
            if (e.Item is ProjectViewModel project)
            {
                var searchText = SearchTextBox.Text?.Trim().ToLower();
                if (string.IsNullOrEmpty(searchText))
                {
                    e.Accepted = true;
                }
                else
                {
                    e.Accepted = project.Name.ToLower().Contains(searchText) ||
                               project.Description.ToLower().Contains(searchText) ||
                               project.RootPath.ToLower().Contains(searchText);
                }
            }
        }

        private void Search_TextChanged(object sender, TextChangedEventArgs e)
        {
            _projectsViewSource.View.Refresh();
        }

        private void SelectAll_Checked(object sender, RoutedEventArgs e)
        {
            foreach (var project in _projects)
            {
                project.IsSelected = true;
            }
            UpdateSelectedCount();
        }

        private void SelectAll_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (var project in _projects)
            {
                project.IsSelected = false;
            }
            UpdateSelectedCount();
        }

        private void ProjectsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateSelectedCount();
        }

        private void UpdateSelectedCount()
        {
            var selectedCount = _projects.Count(p => p.IsSelected);
            SelectedCountText.Text = $"已选择: {selectedCount}";
            DeleteSelectedButton.IsEnabled = selectedCount > 0;
            
            // 更新全选复选框状态
            if (selectedCount == 0)
            {
                SelectAllCheckBox.IsChecked = false;
            }
            else if (selectedCount == _projects.Count)
            {
                SelectAllCheckBox.IsChecked = true;
            }
            else
            {
                SelectAllCheckBox.IsChecked = null; // 部分选中状态
            }
        }

        private void ProjectsDataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (ProjectsDataGrid.SelectedItem is ProjectViewModel selectedProject)
            {
                OpenProject(selectedProject);
            }
        }

        private void OpenProject_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.Tag is ProjectViewModel project)
            {
                OpenProject(project);
            }
        }

        private void OpenProject(ProjectViewModel projectViewModel)
        {
            try
            {
                var project = new Project
                {
                    Id = projectViewModel.Id,
                    Name = projectViewModel.Name,
                    Description = projectViewModel.Description,
                    RootPath = projectViewModel.RootPath,
                    CreatedAt = projectViewModel.CreatedAt,
                    UpdatedAt = projectViewModel.UpdatedAt
                };
                
                ProjectSelected?.Invoke(this, project);
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"打开项目失败: {projectViewModel.Name}");
                MessageBox.Show($"打开项目失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DeleteProject_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.Tag is ProjectViewModel project)
            {
                await DeleteProjectAsync(project);
            }
        }

        private async void DeleteSelected_Click(object sender, RoutedEventArgs e)
        {
            var selectedProjects = _projects.Where(p => p.IsSelected).ToList();
            if (!selectedProjects.Any())
            {
                MessageBox.Show("请先选择要删除的项目", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var result = MessageBox.Show(
                $"确定要删除选中的 {selectedProjects.Count} 个项目吗？\n\n注意：这将删除项目记录，但不会删除项目文件夹。",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                await DeleteProjectsAsync(selectedProjects);
            }
        }

        private async Task DeleteProjectAsync(ProjectViewModel project)
        {
            var result = MessageBox.Show(
                $"确定要删除项目 \"{project.Name}\" 吗？\n\n注意：这将删除项目记录，但不会删除项目文件夹。",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                await DeleteProjectsAsync(new[] { project });
            }
        }

        private async Task DeleteProjectsAsync(IEnumerable<ProjectViewModel> projects)
        {
            try
            {
                UpdateStatus("删除项目中...", Brushes.Orange);
                
                var projectList = projects.ToList();
                var successCount = 0;
                var errorCount = 0;

                foreach (var project in projectList)
                {
                    try
                    {
                        await _dataStorage.DeleteProjectAsync(project.Id);
                        _projects.Remove(project);
                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"删除项目失败: {project.Name}");
                        errorCount++;
                    }
                }

                ProjectCountText.Text = $"共 {_projects.Count} 个项目";
                UpdateSelectedCount();

                if (errorCount == 0)
                {
                    UpdateStatus($"成功删除 {successCount} 个项目", Brushes.Green);
                }
                else
                {
                    UpdateStatus($"删除完成，成功: {successCount}，失败: {errorCount}", Brushes.Orange);
                    MessageBox.Show($"删除完成\n成功: {successCount} 个\n失败: {errorCount} 个", 
                        "删除结果", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除项目失败");
                UpdateStatus("删除失败", Brushes.Red);
                MessageBox.Show($"删除项目失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            LoadProjectsAsync();
        }

        private async void Export_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Title = "导出项目列表",
                    Filter = "CSV文件 (*.csv)|*.csv|文本文件 (*.txt)|*.txt",
                    DefaultExt = "csv",
                    FileName = $"项目列表_{DateTime.Now:yyyyMMdd_HHmmss}"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    await ExportProjectListAsync(saveFileDialog.FileName);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出项目列表失败");
                MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task ExportProjectListAsync(string filePath)
        {
            var csv = new StringBuilder();
            csv.AppendLine("ID,项目名称,描述,路径,创建时间,最后修改时间");

            foreach (var project in _projects)
            {
                csv.AppendLine($"{project.Id},\"{project.Name}\",\"{project.Description}\",\"{project.RootPath}\",{project.CreatedAt:yyyy-MM-dd HH:mm:ss},{project.UpdatedAt:yyyy-MM-dd HH:mm:ss}");
            }

            await File.WriteAllTextAsync(filePath, csv.ToString(), Encoding.UTF8);
            UpdateStatus($"已导出到 {Path.GetFileName(filePath)}", Brushes.Green);
        }

        private async void Cleanup_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UpdateStatus("检查无效项目...", Brushes.Orange);
                
                var invalidProjects = new List<ProjectViewModel>();
                
                foreach (var project in _projects)
                {
                    if (!Directory.Exists(project.RootPath))
                    {
                        invalidProjects.Add(project);
                    }
                }

                if (invalidProjects.Any())
                {
                    var result = MessageBox.Show(
                        $"发现 {invalidProjects.Count} 个无效项目（文件夹不存在）。\n是否删除这些项目记录？",
                        "清理无效项目",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        await DeleteProjectsAsync(invalidProjects);
                    }
                }
                else
                {
                    UpdateStatus("未发现无效项目", Brushes.Green);
                    MessageBox.Show("未发现无效项目", "清理结果", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理无效项目失败");
                UpdateStatus("清理失败", Brushes.Red);
                MessageBox.Show($"清理失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void UpdateStatus(string status, Brush color)
        {
            StatusText.Text = status;
            StatusIcon.Foreground = color;
        }
    }

    /// <summary>
    /// 项目视图模型
    /// </summary>
    public class ProjectViewModel : INotifyPropertyChanged
    {
        private bool _isSelected;

        public ProjectViewModel(Project project)
        {
            Id = project.Id;
            Name = project.Name;
            Description = project.Description;
            RootPath = project.RootPath;
            CreatedAt = project.CreatedAt;
            UpdatedAt = project.UpdatedAt;
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string RootPath { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }

        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
    }
}
